package com.kaifamiao.dao.impl;

import com.kaifamiao.dao.IAccountDao;
import com.kaifamiao.model.Account;
import com.kaifamiao.service.IAccountService;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

/**
 * @author lucien-ma
 * @date 2021/8/25
 * @apiNote
 */
@Repository
public class IAccountDaoImpl implements IAccountDao {

    private QueryRunner queryRunner;

    @Autowired
    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }

    @Override
    public List<Account> findAll() {
        try {
            return queryRunner.query("select * from account", new BeanListHandler<>(Account.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int save(Account account) {
        try {
            return queryRunner.update("insert into account(id, uid, money) values(?, ?, ?)",
                    account.getId(), account.getUid(), account.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    @Override
    public int update(Account account) {
        try {
            return queryRunner.update("update account set money = ? where id = ?",
                    account.getMoney(), account.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    @Override
    public int delete(Integer id) {
        try {
            return queryRunner.update("delete from account where id = ?", id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }
}
